package ar.edu.itba.pod.legajo45129.simul.communication;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import ar.edu.itba.pod.legajo45129.simul.communication.factory.MessageFactory;
import ar.edu.itba.pod.simul.communication.Message;
import ar.edu.itba.pod.simul.communication.MessageListener;

public class MessageListenerImpl implements MessageListener, Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7130665639000042349L;
	
//	private static Logger logger = Logger.getLogger(MessageListenerImpl.class);
	private BlockingQueue<Message> inbox = new LinkedBlockingDeque<Message>();
	private BlockingQueue<Message> broadcastInbox = new LinkedBlockingDeque<Message>();

	
	
	public MessageListenerImpl() throws RemoteException {
		UnicastRemoteObject.exportObject(this, 0);
	}

	@Override
	public Iterable<Message> getNewMessages(String remoteNodeId)
			throws RemoteException {
		
		return broadcastInbox;
	}

	@Override
	public boolean onMessageArrive(Message message) throws RemoteException {

		
		if (inbox.contains(message)) {
			return false;
		}
		
//		if (broadcastInbox.contains(message)) {
//			return false;
//		}
//		
		if (MessageFactory.isForwardable(message)) {
			broadcastInbox.add(message);
		}
		
		inbox.add(message);
		return true;
	}

	
	public BlockingQueue<Message> getInbox() {
		return inbox;
	}


}
